package org.commonsemantics.scigrails.module.users.community

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.lang.builder.HashCodeBuilder 
import org.commonsemantics.scigrails.module.users.security.Role 
import org.commonsemantics.scigrails.module.users.security.Status 
import org.commonsemantics.scigrails.module.users.security.User 

/**
* @author Paolo Ciccarese <paolo.ciccarese@gmail.com>
*/
class UserCommunity implements Serializable {

	Date dateCreated, lastUpdated // Grails automatic timestamping
	
	User user
	Community community
	CommunityRole role
	Status status
		
	boolean equals(other) {
		if (!(other instanceof UserCommunity)) {
			return false
		}

		other.user?.id == user?.id &&
			other.community?.id == community?.id
	}

	int hashCode() {
		def builder = new HashCodeBuilder()
		if (user) builder.append(user.id)
		if (community) builder.append(community.id)
		builder.toHashCode()
	}

	static UserCommunity get(long userId, long communityId) {
		find 'from UserCommunity where user.id=:userId and group.id=:communityId',
			[userId: userId, groupId: communityId]
	}
	
	static def getByUserId(long userId) {
		findAll 'from UserCommunity where user.id=:userId',
			[userId: userId]
	}

	static UserCommunity create(User user, Community community, boolean flush = false) {
		new UserCommunity(user: user, community: community).save(flush: flush, insert: true)
	}

	static boolean remove(User user, Community community, boolean flush = false) {
		UserCommunity instance = UserCommunity.findByUserAndCommunity(user, community)
		instance ? instance.delete(flush: flush) : false
	}

	static void removeAll(User user) {
		executeUpdate 'DELETE FROM UserCommunity WHERE user=:user', [user: user]
	}

	static void removeAll(Community community) {
		executeUpdate 'DELETE FROM UserCommunity WHERE community=:community', [community: community]
	}

	static mapping = {
		id composite: ['community', 'user']
		version false
	}
}
